import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { WeaAlertPage, WeaTableEdit, WeaProgress, WeaRightMenu, WeaTop, WeaSearchGroup, WeaFormItem, WeaTools, WeaInput, WeaBrowser, WeaNewScroll, WeaUpload, WeaError, WeaShare } from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import { Button, Spin } from 'antd';
import * as Fctt from '../constants/BaseFormConstant';
import WeaCrmTableEdit from '../comp/WeaCrmTableEdit';

const comTypes = WeaTools.types;
const getKey = WeaTools.getKey;
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

export default class BaseForm extends React.Component {
  constructor(props) {
    super(props);
  }

  getStore() {

  }

  // render before
  componentWillMount() {
    this.getStore().componentWillMount(this.props);
  }

  // render after
  componentDidMount() {
    this.getStore().componentDidMount(this);
  }

  // component remove before
  componentWillUnmount() {
    this.getStore().componentWillUnmount();
  }

  render() {
    const store = this.getStore();
    const { loading, verified, status, errorMsg, viewTop, titleName, titleIcon, form } = store;
    const loadingCom = <div style={{ position: 'absolute', width: '100%', top: '48%', textAlign: 'center' }}><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@1dqxzn`} spinning={loading} /></div>;
    let content = [];
    if (verified && status == 'failed') {
      content = [(<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@00x62p@alert`} ><div style={{ color: '#000' }}>{errorMsg}</div></WeaAlertPage>)];
    } else if (verified && form && form.isFormInit) {
      if (loading) {
        content.push(loadingCom);
      }
      const params = toJS(this.props.params);
      const formComs = this.getFormComs();
      const formComsSub = this.getFormComsSub();
      const rightMenus = store.getRightMenus();
      const topButtons = store.getTopButtons();

      const shareDialog = this.getShareDialog();

      let topHeight = 0;
      if (viewTop) {
        topHeight = 52;
      }
      const contentHeight = `calc(100% - ${topHeight}px)`;
      content.push(
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@47eoad@rm`} datas={rightMenus}>
          {
            viewTop && (<WeaTop
              ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@f1ay4p@top`}
              loading={loading}
              title={titleName}
              icon={<i className={'icon-coms-crm'} />}
              iconBgcolor="#96358a"
              showDropIcon
              dropMenuDatas={rightMenus}
              buttons={topButtons}
              buttonSpace={10}
            />)
          }
          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@s17cpn@scroll`} height={contentHeight}>
            {formComs}
            {formComsSub}
            {shareDialog }
          </WeaNewScroll>
        </WeaRightMenu>,
      );
    } else {
      content = [loadingCom];
    }
    return content;
  }
    // 分享框
    getShareDialog= () => {
      const store = this.getStore();
      const { shareShareDialogOnCard, showShareDiolog, sellchanceId, sellchanceName, userId } = store;

      const shareDom = (<WeaShare
        ecId={`${this && this.props && this.props.ecId || ''}_WeaShare@md9hls`}
        visible={showShareDiolog}
        onVisibleChange={bool => shareShareDialogOnCard(false)}
        shareParams={{
          resourcetype: 316, // 当前共享数据的类型（同PC浏览按钮的type，例如: 152: 流程
          resourceid: sellchanceId, // 分享数据的id
        }}
        msginfo={[
          {
            sharetitle: sellchanceName, // 消息名片中间一栏显示
            // desc: customerName,//描述，可以不填
            linkurl: `/common/chatResource/view.html?resourcetype=316&resourceid=${sellchanceId}&isfromchatshare=1&sharer=${userId}&firstSharer=${userId}&moduleid=em`, // 消息链接地址（必填）
            canforward: 1, // 消息是否允许转发 1：是（默认） 0：否
            callbackurl: `/api/common/chatResource/addshare?resourcetype=316&resourceid=${sellchanceId}&isfromchatshare=1&firstSharer=${userId}`, // 消息转发回调地址（非必填）
            sharetypename: getLabel(520327, '商机卡片'), // 消息名片上一栏  分享消息的标题栏
            showimage: '/images/p.png',
            sharetype: 'crm',
            shareid: sellchanceId,
            opentype: 1, // 移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
            opentype_pc: 2, // PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
          },
        ]}
      />);
      return shareDom;
    }


    getFormComs() {
      const store = this.getStore();
      const { formItemGroups, form } = store;
      const groups = [];
      if (formItemGroups) {
        const { isFormInit } = form;
        const formParams = form.getFormParams();
        isFormInit && toJS(formItemGroups).map((c,indexGroup) => {
          const items = [];
          c.items.map((field, index) => {
            field = store.reDefineField(field);
            let isunderline = '';
            if (field.viewAttr == '1' || (field.conditionType == 'BROWSER' && field.browserConditionParam.viewAttr == '1')) { field.hasBorder = false; isunderline = 'underline'; } // 只读样式控制
            let dom = '';
            if (field.conditionType == 'UPLOAD') { // 商机附件类型管理，新建和编辑，龙哥处理，onchange事件返回信息
              const key = getKey(field);
              const bindObj = form.$(key);
              dom = (<div className="crm-weaupload"><WeaUpload
                ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@nlwfib@${index}`}
                {...bindObj.bind()}
                {...field}
                {...field.otherParams}
                uploadId={field.domkey[0]}
                uploadUrl="/api/crm/common/fileUpload"
                category="0,0,0"
                autoUpload
                showBatchLoad={false}
                showClearAll={false}
                multiSelection
                listType={field.listType}
                onChange={(ids, lists) => {
                  form.updateFields({ [field.domkey[0]]: { value: `${ids}` } }, false);
                  store.formFieldChange(`${ids}`, field);
                }}
                datas={field.datas || []}
              />
              </div>);
            } else {
              dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@3lsnxt@${index}`} fieldConfig={field} form={form} formParams={formParams} onChange={(v) => { store.formFieldChange(v, field); }} onBlur={(v) => { store.formFieldBlur(v, field); }} />;
            }
            items.push({
              com: (<WeaFormItem
                ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@5lje8q@${index}`}
                error={form.getError(field)}
                tipPosition="bottom"
                label={`${field.label}`}
                labelCol={{ span: `${field.labelcol}` }}
                wrapperCol={{ span: `${field.fieldcol}` }}
                underline={isunderline}
              >
                <div style={{ display: 'table-cell', verticalAlign: 'bottom' }}>
                  <WeaError
                    ecId={`${this && this.props && this.props.ecId || ''}_WeaError@8xlfmi@${index}`}
                    tipPosition="bottom"
                    style={{ width: '100%', display: 'block' }}
                    ref={field.domkey[0]}
                    error={`${'"' + `${field.label}` + '"'}${getLabel(21423, '未填写')}`}
                  >
                    {dom}
                  </WeaError>
                </div>
              </WeaFormItem>),
              col: c.col,
            });
          });
          groups.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@x4hmmp@${indexGroup}`} needTigger title={c.title} showGroup={c.defaultshow} items={items} />);
        });
      }
      return groups;
    }

    getFormComsSub() {
      const store = this.getStore();
      const { form, subTables, customDatas } = store;
      const columns = toJS(subTables[0].columnDefine);
      const productColumns = [
        {
          title: getLabel(15129, '产品名称'),
          isLink: true,
          linkKey: [
            'assetunitid',
            'salesprice',
            'salesnum',
            'totelprice',
          ],
          linkUrl: '',
          com: [{
            formItemType: 'BROWSER',
            labelcol: 6,
            colSpan: 2,
            value: '',
            domkey: [
              'productid',
            ],
            browserType: 38,
            fieldcol: 17,
            label: getLabel(15129, '产品名称'),
            browserConditionParam: {
              isAutoComplete: 1,
              isDetail: 0,
              title: getLabel(15129, '产品名称'),
              linkUrl: '/spa/crm/static/index.html#/main/crm/productView?productId=',
              isMultCheckbox: false,
              hasAdd: false,
              viewAttr: columns[0].viewAttr,
              dataParams: {},
              hasAdvanceSerach: true,
              isSingle: true,
              type: 38,
              icon: 'icon-coms-crm',
              iconBgcolor: '#96358a',
            },
          }],
          width: '20%',
          dataIndex: 'productid',
          key: 'productid',
        },
        {
          title: getLabel(705, '计量单位'),
          com: [{
            formItemType: 'BROWSER',
            labelcol: 6,
            colSpan: 2,
            value: '',
            domkey: [
              'assetunitid',
            ],
            browserType: 69,
            fieldcol: 17,
            label: getLabel(705, '计量单位'),
            browserConditionParam: {
              isAutoComplete: 1,
              isDetail: 0,
              title: getLabel(705, '计量单位'),
              linkUrl: '',
              isMultCheckbox: false,
              hasAdd: false,
              viewAttr: columns[1].viewAttr,
              dataParams: {},
              hasAdvanceSerach: true,
              isSingle: true,
              type: 69,
            },
          }],
          width: '10%',
          dataIndex: 'assetunitid',
          key: 'assetunitid',
        },
        {
          title: getLabel(649, '货币'),
          com: [{
            formItemType: 'BROWSER',
            labelcol: 6,
            colSpan: 2,
            value: '',
            domkey: [
              'currencyid',
            ],
            browserType: 12,
            fieldcol: 17,
            label: getLabel(649, '货币'),
            browserConditionParam: {
              isAutoComplete: 1,
              isDetail: 0,
              title: getLabel(649, '货币'),
              linkUrl: '',
              isMultCheckbox: false,
              hasAdd: false,
              viewAttr: columns[2].viewAttr,
              dataParams: {},
              hasAdvanceSerach: true,
              isSingle: true,
              type: 12,
            },
          }],
          width: '20%',
          dataIndex: 'currencyid',
          key: 'currencyid',
        },
        {
          title: getLabel(1330, '单价'),
          isLink: true,
          linkKey: [
            'salesnum',
            'totelprice',
          ],
          com: [{
            formItemType: 'INPUT',
            labelcol: 6,
            colSpan: 2,
            viewAttr: columns[3].viewAttr,
            length: 10,
            domkey: [
              'salesprice',
            ],
            fieldcol: 17,
            label: getLabel(1330, '单价'),
            otherParams: {
              inputType: 'form',
              detailtype: 3,
              qfws: 2,
              format: {},
              style: {},
            },
          }],
          width: '15%',
          dataIndex: 'salesprice',
          key: 'salesprice',
        },
        {
          title: getLabel(1331, '数量'),
          isLink: true,
          linkKey: [
            'salesprice',
            'totelprice',
          ],
          com: [{
            formItemType: 'INPUT',
            labelcol: 6,
            colSpan: 2,
            viewAttr: columns[4].viewAttr,
            length: 10,
            value: '1',
            domkey: [
              'salesnum',
            ],
            fieldcol: 17,
            label: getLabel(1331, '数量'),
            otherParams: {
              inputType: 'form',
              detailtype: 3,
              qfws: 2,
              format: {},
              style: {},
            },
          }],
          width: '10%',
          dataIndex: 'salesnum',
          key: 'salesnum',
        },
        {
          title: getLabel(2019, '总价'),
          com: [{
            formItemType: 'INPUT',
            labelcol: 6,
            colSpan: 2,
            viewAttr: columns[5].viewAttr,
            length: 10,
            domkey: [
              'totelprice',
            ],
            fieldcol: 17,
            label: getLabel(2019, '总价'),
            otherParams: {
              inputType: 'form',
              detailtype: 3,
              qfws: 2,
              format: {},
              style: {},
            },
          }],
          width: '20%',
          dataIndex: 'totelprice',
          key: 'totelprice',
        },
      ];
      const arr = [];
      const that = this;
      subTables && subTables.length > 0 && toJS(subTables).map((subTable) => {
        arr.push(
          <WeaCrmTableEdit
            ecId={`${this && this.props && this.props.ecId || ''}_WeaCrmTableEdit@8hd49t@wte`}
            ref="table"
            title={getLabel(15115, '产品')}
            showGroup
            needAdd={customDatas.canEdit}
            needCopy={false}
            columns={productColumns}
            datas={subTable.columnData}
            onChange={store.tableDataChange.bind(store)}
            type="addSellChance"
          />);
      });
      return arr;
    }
}
